<?php
/**
 * SVN命令基类
 * @author Alan.H
 */
abstract class Command {
    /**
     * @var null
     */
    protected $file = null;

    /**
     * @var SvnLog
     */
    protected $log = null;

    /**
     * @var null
     */
    protected $params = null;

    /**
     * 命令处理
     * @return mixed
     */
    abstract function execCmd();

    /**
     * @param SvnLog $log
     */
    public function __construct(SvnLog $log = null) {
        $log && $this->setLog($log);
    }

    /**
     * @param SvnLog $log
     * @return $this
     */
    public function setLog(SvnLog $log) {
        $this->log = $log;
        return $this;
    }

    /**
     * @return null
     */
    public function getFile() {
        return $this->file;
    }

    /**
     * @param $key
     * @param $value
     * @return $this
     */
    public function setParam($key, $value) {
        if (is_array($key)) {
            foreach ($key as $k => $v) {
                $this->params[$k] = $v;
            }
            return $this;
        }

        $this->params[$key] = $value;
        return $this;
    }

    /**
     * @param null $key
     * @return null
     */
    public function getParam($key = null) {
        return $key ? $this->params[$key] : $this->params;
    }

    /**
     * @param $method
     * @param $args
     * @throws Exception
     */
    public function __call($method, $args) {
        $m = strtolower(substr($method, 0, 3));
        switch ($m) {
            case 'set':
                $key = $this->_underscore(substr($method, 3));
                return $this->setParam($key, isset($args[0]) ? $args[0] : null);

            case 'get':
                $key = $this->_underscore(substr($method, 3));
                return $this->getParam($key, isset($args[0]) ? $args[0] : null);

            default:
                break;
        }
        throw new BadMethodCallException('Invalid method ' . get_class($this) . "::" . $method);
    }

    /**
     * @param $name
     * @return string
     */
    protected function _underscore($name) {
        return strtolower(preg_replace('/(.)([A-Z])/', "$1_$2", $name));
    }

    /**
     * @param $dateString
     * @return string
     */
    protected function formatDate($dateString) {
        $datetime = new DateTime($dateString);
        $datetime->setTimezone(new DateTimeZone('Asia/Shanghai'));
        return $datetime->format('Y-m-d H:i:s');
    }
}